define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'xiluedu/coupon/index' + location.search,
                    add_url: 'xiluedu/coupon/add',
                    edit_url: 'xiluedu/coupon/edit',
                    del_url: 'xiluedu/coupon/del',
                    users_url: 'xiluedu/coupon/users',
                    user_coupons_url: 'xiluedu/coupon/user_coupons',
                    multi_url: 'xiluedu/coupon/multi',
                    table: 'xiluedu_coupon',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                search:false,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Name'), operate: 'LIKE'},
                        {field: 'type', title: __('Type'), searchList: {"1":__('Type 1'),"2":__('Type 2')}, formatter: Table.api.formatter.normal},
                        {field: 'type_value', title: __('类型值'),operate:false,formatter:function (value,row) {
                                if(row.type === "1"){
                                    return row.money+'元';
                                }
                                return row.discount/10 +'折';
                            }},
                        // {field: 'receive_time', title: __('领取时间'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: function (value,row) {
                        //         return row.receive_start_time_text +'至'+ row.receive_end_time_text;
                        //     }},
                        {field: 'use_time', title: __('使用时间'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: function (value,row) {
                                return row.use_start_time_text +'至'+ row.use_end_time_text;
                            }},
                        {field: 'max_count', title: __('Max_count')},
                        {field: 'at_least', title: __('At_least'), operate:'BETWEEN'},
                        //{field: 'per_count', title: __('Per_count')},
                        // {field: 'freight_type', title: __('Freight_type'), searchList: {"1":__('Freight_type 1'),"2":__('Freight_type 2'),"3":__('Freight_type 3'),"4":__('Freight_type 4')}, formatter: Table.api.formatter.normal},
                        {field: 'range_status', title: __('Range_status'), searchList: {"1":__('Range_status 1'),"2":__('Range_status 2')}, formatter: Table.api.formatter.status},
                        {field: 'status', title: __('Status'), searchList: {"0":__('Status 0'),"1":__('Status 1')}, formatter: Table.api.formatter.status},
                        //  {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table,buttons:[
                                {
                                    name: 'users',
                                    text: __('发放'),
                                    title: __('发放'),
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    icon: 'fa',
                                    url: function (row) {
                                        return $.fn.bootstrapTable.defaults.extend.users_url+'?coupon_id='+row.id;
                                    },
                                    visible: function (row) {
                                        //返回true时按钮显示,返回false隐藏
                                        return true;
                                    }
                                },
                                {
                                    name: 'user_coupons',
                                    text: __('记录'),
                                    title: __('记录'),
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    icon: 'fa',
                                    url: function (row) {
                                        return $.fn.bootstrapTable.defaults.extend.user_coupons_url+'?coupon_id='+row.id;
                                    },
                                    visible: function (row) {
                                        //返回true时按钮显示,返回false隐藏
                                        return true;
                                    }
                                }
                            ] , events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
            //选择
            $(document).on('click','.course-choose',function () {
                var that = $(this);
                var url = that.attr('data-url') || 'xiluedu/course/selects';
                var course_ids_obj = $("[name^=course_ids]");
                var selectids = [];
                for (var i=0;i<course_ids_obj.length;i++) {
                    selectids[i] = $(course_ids_obj[i]).val();
                }
                parent.Fast.api.open(url + "?ids="+selectids+"&multiple=true", __('Choose'), {
                    callback: function (data) {
                        console.log(data);
                        var html = htmlTemplate(data.data);
                        $('.table tbody').html(html);
                    }
                });
                return false;
            });
            $(document).on('click','.course_detail',function () {
                var course_id = $(this).data('course_id');
                parent.Fast.api.open("xiluedu/course/edit/ids/"+course_id, __('详情'));
            })
            $(document).on('click','.course_del',function () {
                var that = $(this);
                Layer.confirm("确认删除",function (index2) {
                    that.parents("tr").remove();
                    Layer.close(index2);
                })
            })
        },
        edit: function () {
            Controller.api.bindevent();
            //选择
            $(document).on('click','.course-choose',function () {
                var that = $(this);
                var url = that.attr('data-url') || 'xiluedu/course/selects';
                var course_ids_obj = $("[name^=course_ids]");
                var selectids = [];
                for (var i=0;i<course_ids_obj.length;i++) {
                    selectids[i] = $(course_ids_obj[i]).val();
                }
                parent.Fast.api.open(url + "?ids="+selectids+"&multiple=true", __('Choose'), {
                    callback: function (data) {
                        console.log(data);
                        var html = htmlTemplate(data.data);
                        $('.table tbody').html(html);
                    }
                });
                return false;
            });
            $(document).on('click','.course_detail',function () {
                var course_id = $(this).data('course_id');
                parent.Fast.api.open("xiluedu/course/edit/ids/"+course_id, __('详情'));
            })
            $(document).on('click','.course_del',function () {
                var that = $(this);
                Layer.confirm("确认删除",function (index2) {
                    that.parents("tr").remove();
                    Layer.close(index2);
                })
            })
        },

        users: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'xiluedu/coupon/users'+location.search,
                    send_url: 'xiluedu/coupon/send?coupon_id='+Config.coupon_id,
                    table: 'user',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), sortable: true,operate:false},
                        {field: 'nickname', title: __('Nickname'), operate: false},
                        {field: 'mobile', title: __('手机号'), operate: false},
                        {field: 'avatar', title: __('头像'), events: Table.api.events.image, formatter: Table.api.formatter.image, operate: false},
                        {field: 'logintime', title: __('登录时间'), formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange', autocomplete:false, sortable: true},
                        // {field: 'jointime', title: __('加入时间'), formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange', sortable: true},
                        {field: 'status', title: __('Status'), formatter: Table.api.formatter.status, searchList: {normal: __('Normal'), hidden: __('Hidden')},operate:false},
                        {field: 'operate', title: __('Operate'), table: table,buttons:[
                                {
                                    name: 'ajax',
                                    text: __('发放'),
                                    title: __('发放'),
                                    classname: 'btn btn-xs btn-success btn-magic btn-ajax',
                                    icon: 'fa fa-magic',
                                    confirm:'确认发放?',
                                    url: function (row) {
                                        return $.fn.bootstrapTable.defaults.extend.send_url+'&user_ids='+row.id
                                    },
                                    success: function (data, ret) {
                                        Toastr.success('发放成功');
                                        return false;
                                    },
                                    error: function (data, ret) {
                                        Layer.alert(ret.msg);
                                        return false;
                                    }
                                },
                            ], events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            $('.btn-all,.btn-part').click(function(){
                var logintime = $('[name=logintime]').val() || 0;
                var type = 'part';
                if($(this).hasClass('btn-all')){
                    type = 'all';
                }
                if(type === 'part'){
                    var ids = Table.api.selectedids(table)
                    if(ids.length<=0){
                        Toastr.error('未选择发放人');
                    }
                }
                var msg = '确定发放优惠券';
                switch (type){
                    case 'all':
                        msg = '全部发放仅支持登录时间条件发放';break;
                }
                Layer.confirm(msg, function(index){
                    layer.close(index);
                    Fast.api.ajax({url:$.fn.bootstrapTable.defaults.extend.send_url,data:{type: type,logintime:logintime}},function (data,ret) {
                        Toastr.success('发放成功');
                        return false;
                    },function (data,ret) {
                        Layer.alert(ret.msg);
                        return false;
                    })
                })
            })


        },
        user_coupons: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'xiluedu/coupon/user_coupons'+location.search,
                    table: 'xiluedu_user_coupon',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                search:false,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), sortable: true,operate:false},
                        {field: 'coupon_id', title: __('优惠券id'),visible:false},
                        {field: 'user.nickname', title: __('Nickname'), operate: 'LIKE'},
                        {field: 'user.mobile', title: __('手机号'), operate: 'LIKE'},
                        {field: 'user.avatar', title: __('头像'), events: Table.api.events.image, formatter: Table.api.formatter.image, operate: false},
                        {field: 'use_status', title: __('Status'), formatter: Table.api.formatter.status, searchList: {'0': __('未使用'), '1': __('已使用')}},
                        {field: 'createtime', title: __('发放时间'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'usetime', title: __('使用时间'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        api: {
            bindevent: function () {

                $(document).on('click','[name^="row[type]"]',function () {
                    var value = $(this).val();
                    if(value === "2"){
                        $('#c-money').parents(".form-group").addClass("hide");
                        $('#c-discount').parents(".form-group").removeClass("hide");
                    }else{
                        $('#c-money').parents(".form-group").removeClass("hide");
                        $('#c-discount').parents(".form-group").addClass("hide");
                    }
                });

                $(document).on('click','[name^="row[range_status]"]',function () {
                    var value = $(this).val();
                    if(value === "2"){
                        $('.range-courses').removeClass("hide");
                    }else{
                        $('.range-courses').addClass("hide");
                    }
                });

                Form.api.bindevent($("form[role=form]"));

            }
        }
    };
    return Controller;
});

function htmlTemplate(data) {
    var html = '';

    for(var i=0;i<data.length;i++){
        var img = Fast.api.fixurl(data[i].thumb_image);
        html += '<tr>';
        html += '<input type="hidden" name="course_ids[]" value="'+data[i].id+'">';
        html += '<td><img width="40px" src="'+img+'" alt=""></td>';
        html += '<td>'+data[i].name+'</td>';
        html += '<td><p><button type="button" class="btn btn-danger course_del" data-course_id="'+data[i].id+'"><i class="fa fa-trash"></i></button>';
        html += '<button type="button" class="btn btn-warning course_detail" data-course_id="'+data[i].id+'"><i class="fa fa-eye"></i></button></p></td>';
        html += '</tr>';
    }
    return html;
}
